<?php
class MController extends MComponent {
    /**
     * @var MView
     */
    private $_view;
    
    protected $_template = NULL;
    protected $_template_stylesheets = array();
    protected $_template_scripts = array();

    public function __construct($request, $response = NULL) {
        $this->_request = $request;
        if (!isset($response))
            $this->_response = new MResponse();
        else
            $this->_response = $response;
        $this->_view = new MView($this->_request->getModule(),$this->_request->getController(), $this->_request->getAction());
        $this->_view->isAdmin($this->_request->isAdmin());
    }

    public function assign($name, $value) {
        $this->_response->assignVar($name, $value);
    }

    /**
     * Render the response to the user with the current template
     * @param String $file (optional) : Filename of the view to render
     * @param Array $vars (optional) : Parameters/Variables to set for the view
     */
    public function render($file = NULL, $vars = array()){
        if ($this->_template !== NULL){
            MTemplate::getInstance()->setTemplate($this->_template);
        }
        if (!empty($this->_template_stylesheets)){
            MTemplate::getInstance()->setStylesheets($this->_template_stylesheets);
        }
        if (!empty($this->_template_scripts)){
            MTemplate::getInstance()->setScripts($this->_template_scripts);
        }
        if ($this->_request->isAdmin()){
            $this->_response->setModule(MApplication::ADMIN_MODULE);
        } else {
            $this->_response->setModule($this->_request->getModule());
        }
        $this->_response->setStylesheet($this->_view->renderStylesheets());
        $this->_response->setScript($this->_view->renderScripts());
        $this->_response->setContent($this->_view->render($file, $vars));
        $this->_response->render();
    }

    /**
     * Render the response to the user (only the view)
     * @param String $file (optional) : Filename of the view to render
     * @param Array $vars (optional) : Parameters/Variables to set for the view
     */
    public function renderPartial($file = NULL, $vars = array(), $return = false){
        $this->_response->setModule($this->_request->getModule());
        $this->_response->setContent($this->_view->render($file, $vars));
        return $this->_response->renderPartial($return);
    }

    public function __destruct() {
        unset($this->_template_scripts);
        unset($this->_template_stylesheets);
    }

}
?>
